<?php
/**
 * Created by PhpStorm.
 * User: XZR
 * Date: 2018/8/1
 * Time: 15:21
 */

namespace Api\Controller;
use Api\Model\UserModel;
use Api\Model\WeixinUserModel;
use Common\Controller\BaseController;
use Common\Util\EncryUtils;
use Think\Model;


class AuthController extends  BaseController
{
    public $userId = 0;
    public $weixinUser = null;
    public function _initialize(){
        //$this->_validateurl();
        $this->log();
        $this->_initlogin();

    }

    //不用验证登录的action
    private static $fakeAction = [
        'Record@getList',
        'User@register',
        'Record@detail',
        'RecordDetail@getImage',

    ];

    //不用验证token的action
    private static $tokenAction = [
        'Record@detail',
        'RecordDetail@get'

    ];

    //需要验证是否授权获取信息的接口
    private static $needCheckAuth = [
        'User@register',
    ];


    public function _initlogin(){
        $token = $this->getPostParam("token", "");
        $openid = EncryUtils::decrypt($token);

/*        if(in_array(CONTROLLER_NAME . '@' . ACTION_NAME, self::$tokenAction) && !$token){
            return;
        }*/
        if(!$this->getUser($openid) || $this->weixinUser['is_auth']!=1){
            if(in_array(CONTROLLER_NAME . '@' . ACTION_NAME, self::$needCheckAuth)){
                $rst['msg']="token失效";
                $rst['result']=-100;
                $this->formatjson($rst);
            }

        }

        if(!$this->userId){
            if (!in_array(CONTROLLER_NAME . '@' . ACTION_NAME, self::$fakeAction)) {
                $rst['msg']="未注册,请注册";
                $rst['result']=-101;
                $this->formatjson($rst);
            }
        }




    }

    public function getUser($openid){
        $obj = WeixinUserModel::singleton()->getOneByOpenid($openid);
        if($obj){
            $this->weixinUser = $obj;//微信信息
            $user = UserModel::singleton()->getByOpenid($openid);
            if($user){
                $this->userId = $user['id'];//注册过存入用户id
            }
            return true;
        }else{
            return false;
        }
    }

    private function log()
    {
        $body = json_decode(file_get_contents('php://input'));
        $request = [
            'param' => $_REQUEST,
        ];
        $body and $request['body'] = $body;
        (new Model())->table('__API_LOG__')->add([
            'action' => CONTROLLER_NAME . '@' . ACTION_NAME,
            'method' => $_SERVER['REQUEST_METHOD'],
            'request' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }
}
